/*!
 *
 * @version        1
 * @since         
 * @author         
 * @documentation   
 * $Id: e152c63455205c211632f5a81a4e951c69fbf2c5 $
 *
 */


/* IE8 等 不支持 ARRAY indexOf 的方法 */	
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

  	

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}




// 过滤 输入的TAGS
function findTags( tags , tag ){
    for (var i = 0; i < tags.length; i++) {
        var el = tags[i];
        if( el == tag )
            return true;
         
    }
    return false;
}

// 在 tags 中查找 array2 是否有元素命中
// 有 返回 true
function checkTagInTags( tags , array2 ){
    for (var i = 0; i < array2.length; i++) {
        var item = array2[i];
        if(item ){
            if ( findTags(tags, item))
                return true;
        }
    };

    return false;
}





/* IE8 等 不支持 String.trim() 的方法 */	
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}	

/* 
 将String类型解析为Date类型.  
  parseDate(' 2006-1-1 15:14:16.254 ') return new Date(2006,0,1,15,14,16,254)  
   parseDate('不正确的格式') retrun null  
*/  
function _parseDate(str){   
	if(typeof str == 'string'){   
		var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);   
		if(results && results.length>3)   
			return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]));    
		results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);   
		if(results && results.length>6)   
			return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),parseInt(results[4]),parseInt(results[5]),parseInt(results[6]));    
		results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);   
		if(results && results.length>7)   
			return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),parseInt(results[4]),parseInt(results[5]),parseInt(results[6]),parseInt(results[7]));    
     
		results = str.match(/^ *(\d{4})-(\d{2})-(\d{2}) +(\d{2}):(\d{2}):(\d{2})\.(\d{3}) *$/);  
		if(results && results.length>7)   
			return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),
				parseInt(results[4]),parseInt(results[5]),parseInt(results[6]),parseInt(results[7]));    
  }   
  return null;   
}  
Date.prototype.format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
function _parseDateyyyyMMdd(str){   
  if(typeof str == 'string'){   
      
	var results = str.match(/^ *(\d{4})(\d{2})(\d{2}) *$/);  
	if(results && results.length>3)   
		return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),
			0,0,0,0);    
  }   
  return null;   
}  

/**
 * 分析 yyyyMMddhh类型的时间字符串，返回Date对象
 * @param  {[type]} str [description]
 * @return {[type]}     [description]
 */
function _parseDateyyyyMMddhh(str){   
  if(typeof str == 'string'){   
      
	var results = str.match(/^ *(\d{4})(\d{2})(\d{2})(\d{2}) *$/);  
	if(results && results.length>4)   
		return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),
			parseInt(results[4]),0,0,0);    
  }   
  return null;   
}  

function _parseDateyyyyMM(str){   
  if(typeof str == 'string'){   
      
	var results = str.match(/^ *(\d{4})(\d{2}) *$/);  
	if(results && results.length>2)   
		return new Date(parseInt(results[1]),parseInt(results[2])-1  ,1,
			0,0,0,0);    
  }   
  return null;   
}   


function _isInt(n) {
   return n % 1 === 0;
}
	
// 判断是否 数组	
function _isArray( value ){
 
	return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
 

}	



 
function _checkPage( page ){
	var _script = /<script>/gi;
	if(_script.test(page))
		return true;
	else
		return false;
}


/* 在一个 array 中去重 */
function _uniqueArray(a) {
	var result = [];
	for( var i = 0 ;i < a.length ;i++){
		var find = result.indexOf(a[i])
		if(find<0)
			result.push(a[i]);
	}
	return result;
};

  
/* 如果字符串过长，截取后半部分内容显示 */  
function _retrieveEndStr( str , len1  , append ){
	var len = str.length;
	if(len > len1){
		if( append == undefined  )
			append = '..';
		 return append + str.substr( len - len1);
	}else {
		return str;
	}
	
}

function _skipBeginStr( str , len1 , append ){
	var len = str.length;
	if(len > len1){
		if( append == undefined  )
			append = '..';
		 return append + str.substr( len1 , len - len1);
	}else {
		return str;
	}
	
}

function _startWith( str , val ){
 	
	if( !str )
		return false;
	if( !val )
		return false;
		
		
	 
			
	if( _isArray(val)){

		for( var i =0 ;i < val.length ;i++){
			if(val[i])
			{
				var find = str.indexOf(val[i]);
				if(find == 0)
					return true;
			}
		}
		
		return false;
	
	}else {
		var find = str.indexOf(val);
		if(find == 0)
			return true;
		return false;
			 
	}
		 
		

}

/**
 * 将 输入的 array（如果包含 ，的字符串将分割） 或 string（，分割）的字符串，
 * 转化为数组 
 * @param  {[type]} values [description]
 * @return {[type]}        [返回 array]
 */
function _paramstoArrays(  values ){
	var _ret = [];
	if(   values ) {
 		if( _isArray(values)){

			for( var i =0 ;i < values.length ;i++){
				if(values[i]){
					var value = values[i];
					var _vals =  value.split(',');
					if(_vals){
						for( var i = 0;i< _vals.length;i++){
							if(_vals[i])
								_ret.push(_vals[i]);
						}
					}
					
				}
			}
		
		}else {

			if( typeof values == 'string'){
				var _vals =  values.split(',');
				if(_vals){
					for( var i = 0;i< _vals.length;i++){
						if(_vals[i])
							_ret.push(_vals[i]);
					}
				}
			}else{
				_ret.push(values);
			}

			
			 
		}
	}
	return _ret;
}


/**
 * append name and value to _url , 
 * if value is array , then  _url += name = value[1] & name= value[2]
 * if value is string split with , 
 * if value is single string _url += name = value ;
 * @param  {[type]} _url  [description]
 * @param  {[type]} name  [description]
 * @param  {[type]} value [description]
 * @return {[type]}       [description]
 */
function _appendUrlList( _url , name , value){
    if( name && value && value!=null) {
        
        if( _isArray(value)){

            for( var i =0 ;i < value.length ;i++){
                if(value[i])
                    _url += '&' + name +'='+ encodeURIComponent(value[i]);
            }
        
        }else {

            if( typeof value == 'string'){
                var _vals =  value.split(',');
                if(_vals){
                    for( var i = 0;i< _vals.length;i++){
                        if(_vals[i])
                            _url += '&' + name +'='+ encodeURIComponent(_vals[i]);
                    }
                }
            }else{
                _url += '&' + name +'='+ encodeURIComponent(value);
            }

            
             
        }
    }
    return _url;
}


/* 通过属性名，得到该属性的配置 */
function _getAttrType(type){
	for(var key in _INC_ATTR_TYPE){
		if(key == type)
			return _INC_ATTR_TYPE[key];
	}
	return null;
}	




////////////////////////////////////////////////////////////////////////////////////////////////////
///
///


// 月+-
function _addMonth( date1, offset){
    
    if( offset == undefined )
        offset = 0 ;

    date = new Date(date1);
    
    if( offset == 0 )
        return date ;

    var month = date.getMonth() + offset ;    
    date.setMonth(month);

    return date;

}


function _addYear( date1, offset){
    
    if( offset == undefined )
        offset = 0 ;

    date = new Date(date1);
    
    if( offset == 0 )
        return date ;

    var year = date.getFullYear() + offset ;    
    date.setFullYear(year);

    return date;

}


function toYear( date ){
    return date.format('yyyy');
}

function toMonth( date ){
    return date.format('yyyyMM');
}


// 得到当前月， yyyyMM 字符串
function getCurrentMonth(offset){
    
    if( offset == undefined )
        return toMonth( new Date());
    else{

        return  toMonth( _addMonth(new Date(), offset));
    }
}

function getCurrentYear( offset ){
	if( offset == undefined )
		return toYear(new Date());
	else{
		return toYear(_addYear(new Date(),offset));
	}
}
	
 
/*
    cycle.js
    2016-05-01

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint eval, for */

/*property
    $ref, decycle, forEach, isArray, keys, length, push, retrocycle, stringify,
    test
*/

if (typeof JSON.decycle !== "function") {
    JSON.decycle = function decycle(object, replacer) {
        "use strict";

// Make a deep copy of an object or array, assuring that there is at most
// one instance of each object or array in the resulting structure. The
// duplicate references (which might be forming cycles) are replaced with
// an object of the form

//      {"$ref": PATH}

// where the PATH is a JSONPath string that locates the first occurance.

// So,

//      var a = [];
//      a[0] = a;
//      return JSON.stringify(JSON.decycle(a));

// produces the string '[{"$ref":"$"}]'.

// If a replacer function is provided, then it will be called for each value.
// A replacer function receives a value and returns a replacement value.

// JSONPath is used to locate the unique object. $ indicates the top level of
// the object or array. [NUMBER] or [STRING] indicates a child element or
// property.

        var objects = [];   // Keep a reference to each unique object or array
        var paths = [];     // Keep the path to each unique object or array

        return (function derez(value, path) {

// The derez function recurses through the object, producing the deep copy.

            var i;          // The loop counter
            var nu;         // The new object or array

// If a replacer function was provided, then call it to get a replacement value.

            if (replacer !== undefined) {
                value = replacer(value);
            }

// typeof null === "object", so go on if this value is really an object but not
// one of the weird builtin objects.

            if (
                typeof value === "object" && value !== null &&
                !(value instanceof Boolean) &&
                !(value instanceof Date) &&
                !(value instanceof Number) &&
                !(value instanceof RegExp) &&
                !(value instanceof String)
            ) {

// If the value is an object or array, look to see if we have already
// encountered it. If so, return a {"$ref":PATH} object. This is a hard
// linear search that will get slower as the number of unique objects grows.
// Someday, this should be replaced with an ES6 WeakMap.

                i = objects.indexOf(value);
                if (i >= 0) {
                    return {$ref: paths[i]};
                }

// Otherwise, accumulate the unique value and its path.

                objects.push(value);
                paths.push(path);

// If it is an array, replicate the array.

                if (Array.isArray(value)) {
                    nu = [];
                    value.forEach(function (element, i) {
                        nu[i] = derez(element, path + "[" + i + "]");
                    });
                } else {

// If it is an object, replicate the object.

                    nu = {};
                    Object.keys(value).forEach(function (name) {
                        nu[name] = derez(
                            value[name],
                            path + "[" + JSON.stringify(name) + "]"
                        );
                    });
                }
                return nu;
            }
            return value;
        }(object, "$"));
    };
}


if (typeof JSON.retrocycle !== "function") {
    JSON.retrocycle = function retrocycle($) {
        "use strict";

// Restore an object that was reduced by decycle. Members whose values are
// objects of the form
//      {$ref: PATH}
// are replaced with references to the value found by the PATH. This will
// restore cycles. The object will be mutated.

// The eval function is used to locate the values described by a PATH. The
// root object is kept in a $ variable. A regular expression is used to
// assure that the PATH is extremely well formed. The regexp contains nested
// * quantifiers. That has been known to have extremely bad performance
// problems on some browsers for very long strings. A PATH is expected to be
// reasonably short. A PATH is allowed to belong to a very restricted subset of
// Goessner's JSONPath.

// So,
//      var s = '[{"$ref":"$"}]';
//      return JSON.retrocycle(JSON.parse(s));
// produces an array containing a single element which is the array itself.

        var px = /^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;

        (function rez(value) {

// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.

            if (value && typeof value === "object") {
                if (Array.isArray(value)) {
                    value.forEach(function (element, i) {
                        if (typeof element === "object" && element !== null) {
                            var path = element.$ref;
                            if (typeof path === "string" /*&& px.test(path)*/) {
                                value[i] = eval(path);
                            } else {
                                rez(element);
                            }
                        }
                    });
                } else {
                    Object.keys(value).forEach(function (name) {
                        var item = value[name];
                        if (typeof item === "object" && item !== null) {
                            var path = item.$ref;
                            if (typeof path === "string" /*&& px.test(path)*/) {
                                value[name] = eval(path);
                            } else {
                                rez(item);
                            }
                        }
                    });
                }
            }
        }($));
        return $;
    };
}

